﻿using ASmile.DBModel;
using ASmile.Extend;
using ASmile.ORM.Cores;

namespace ASmile.Com.Da
{
    public class UserManageBLL : BLLCrudBase<Sys_User>, IUserManageBLL //IBLLCrud<Sys_User>
    {
        protected override void SetQuery(QueryCondition<Sys_User> query, ArgPageData arg)
        {
            if (!arg.SearchVal.IsEmpty())
            {
                string likeStr = $"%{arg.SearchVal}%";
                query.WhereAnd(s =>
                    s.WEx_Like(s.LoginName, likeStr) ||
                    s.WEx_Like(s.UserName, likeStr));
            }
            query.OrderBy(s => s.AddTime);
        }

        protected override ApiResult<string> VerifyModel(Sys_User user, bool isAdd)
        {
            if (!isAdd && user.Id.IsEmpty())
            {
                return RetErr(nameof(user.LoginName), "更新失败，参数错误");
            }
            if (user.LoginName.IsEmpty())
            {
                return RetErr(nameof(user.LoginName), "登陆名不能为空");
            }
            if (user.UserName.IsEmpty())
            {
                return RetErr(nameof(user.UserName), "用户名不能为空");
            }
            if (DB.QueryExist<Sys_User>(s => s.Id != user.Id && s.LoginName == user.LoginName))
            {
                return RetErr(nameof(user.LoginName), "登录名已存在");
            }
            if (DB.QueryExist<Sys_User>(s => s.Id != user.Id && s.UserName == user.UserName))
            {
                return RetErr(nameof(user.UserName), "用户名已存在");
            }
            if (isAdd)
            {
                user.Id = NewId();
                user.LoginPwd = "123"; //AppConfig.THIS.UserDefaultPwd;
                return RetOK(user.Id, "新增成功");
            }
            else
            {
                return RetOK(string.Empty, "更新成功");
            }
        }
    }
}